package com.concurrent.aqslock.part9.tryrw;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 简单的demo，比对ReentrantReadWriteLock和synchronized性能
 */
public class RwDemo {

    private ReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock getLock = lock.readLock();
    private final Lock setLock = lock.writeLock();
    private int number;


    // 使用synchronized对象锁进行读取锁定
    public synchronized int synGetNumber() {
        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return number;
    }

    // 使用synchronized对象锁进行修改锁定
    public synchronized void synSetNumber(int number) {
        try {
            Thread.sleep(10);
            this.number = number;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 使用ReentrantReadWriteLock的读锁进行读取锁锁定
    public int rwGetNumber() {
        try {
            getLock.lock();
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            getLock.unlock();
        }

        return number;
    }

    // 使用ReentrantReadWriteLock的写锁进行写锁锁定
    public void rwSetNumber(int number) {
        try {
            setLock.lock();
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            setLock.unlock();
        }
        this.number = number;
    }


    public static void main(String[] arg0) {
        RwDemo rwDemo = new RwDemo();
        for (int i = 0; i < 5; ++i) {
            for (int k = 0; k < 3; ++k) {
                new Thread(() -> {
                    long start = System.currentTimeMillis();
                    for (int j = 0; j <= 10; ++j) {
//                        rwDemo.rwGetNumber();
                        rwDemo.synGetNumber();
                    }
                    System.out.println(Thread.currentThread().getName()
                            + "读商品数据耗时：" + (System.currentTimeMillis() - start) + "ms---------");
                }).start();
            }
            new Thread(() -> {
                long start = System.currentTimeMillis();
                for (int j = 0; j <= 10; ++j) {
                    Random r = new Random();
//                    rwDemo.rwSetNumber(r.nextInt());
                    rwDemo.synSetNumber(r.nextInt());
                }
                System.out.println(Thread.currentThread().getName()
                        + "写商品数据耗时：" + (System.currentTimeMillis() - start) + "ms---------");
            }).start();
        }
    }
}
